<template>
  <!-- 坞修第二步 -->
  <div class="step2">
    <div class="top">
      <div class="flexec">
        <!-- <el-button
          type="primary"
          @click="handleBack"
        >
          {{ t(`dockRepair.Back`) }}
        </el-button> -->
        <el-button type="primary" @click="handleSave('save')">
          {{ t(`dockRepair.Save`) }}
        </el-button>
        <el-button type="primary" @click="handleNext">
          {{ t(`dockRepair.NextStep`) }}
        </el-button>
      </div>
      <div class="flexcc mt-2">
        <div class="bold">
          <span>{{ t(`dockRepair.step2`) }}:</span>
          <span>{{ store.stepDesc }}</span>
        </div>
      </div>
    </div>

    <el-form ref="formEl" :model="ruleForm" :rules="rules" label-width="0px" label-position="left" hide-required-asterisk>
      <div class="grid-1">
        <div class="module" style="padding-bottom: 10px">
          <el-form-item prop="quoteOrderCurrency" :label="t('dockRepair.label3')" label-width="auto">
            <el-select v-model="ruleForm.quoteOrderCurrency" class="wp-100" :placeholder="t('select_p')" filterable clearable>
              <el-option v-for="item in dictData['currency']" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
            </el-select>
          </el-form-item>
        </div>
        <div class="module" style="padding-bottom: 10px">
          <el-form-item prop="payCurrency" :label="t('dockRepair.label4')" label-width="auto">
            <el-select v-model="ruleForm.payCurrency" class="wp-100" :placeholder="t('select_p')" filterable clearable>
              <el-option v-for="item in dictData['currency']" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
            </el-select>
          </el-form-item>
        </div>
      </div>

      <div class="module mt-3 keyword">
        <div class="title">
          <div class="flexsc">
            <div class="flexcc mr-1">{{ t('dockRepair.label2') }}</div>
            <el-button type="primary" icon="Plus" style="width: 80px; min-width: auto" @click="addKeyWordDialog = true" />
          </div>
        </div>
        <div class="con mt-2 flexsb">
          <div :class="['item', 'flexcc']" v-for="item in info.dockImportProjectBoList" :key="item.projectId">
            {{ item.projectName }}
          </div>
        </div>
      </div>

      <div class="module mt-3">
        <div class="title">{{ t('dockRepair.label1') }}</div>
        <el-form-item prop="remark" class="mt-2">
          <el-input v-model="ruleForm.remark" type="textarea" maxlength="500" show-word-limit :autosize="{ minRows: 3 }" />
        </el-form-item>
      </div>
    </el-form>

    <div class="list mt-5">
      <div class="group flexsc">
        <!-- <div class="mr-4" v-if="locale === 'zh-CN'">已选 1 项</div>
        <div class="mr-4" v-if="locale === 'en'">1 item selected</div> -->

        <!-- 系统维修项目 -->
        <!-- <el-button
          type="primary"
          @click="handleAdd('0')"
          :disabled="setBtnDiasbled('0')"
        >
          +{{ t(`dockRepair.btn1`) }}
        </el-button> -->

        <!-- 自定义维修项目 -->
        <el-button type="primary" @click="handleAdd('2')" :disabled="setBtnDiasbled('2')"> +{{ t(`dockRepair.btn2`) }} </el-button>

        <!-- 说明 -->
        <el-button type="primary" @click="handleAdd('1')" :disabled="setBtnDiasbled('1')"> +{{ t(`dockRepair.btn3`) }} </el-button>

        <!-- 附加项 -->
        <!-- <el-button
          type="primary"
          @click="handleAdd('3')"
          :disabled="setBtnDiasbled('3')"
        >
          +{{ t(`dockRepair.btn4`) }}
        </el-button> -->

        <el-button type="primary" :disabled="setBtnDiasbled('3')" @click="handleAddItemSteelStructure()"> +{{ t(`dockRepair.btn11`) }} </el-button>
        <el-button type="primary" @click="handleAddItemPipeline()" :disabled="setBtnDiasbled('3')"> +{{ t(`dockRepair.btn9`) }} </el-button>
        <el-button type="primary" :disabled="setBtnDiasbled('3')" @click="handleAddItemValve()"> +{{ t(`dockRepair.btn10`) }} </el-button>
      </div>

      <div :class="['table', 'mt-2', locale]" @mouseover.once="alertTipDialog = true">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table-v2 ref="tableRef" :columns="columns" :data="tableData" :width="width" :height="height" :row-class="setRowClass" @scroll="onScroll" fixed />
          </template>
        </el-auto-resizer>
      </div>

      <div v-show="isEnd" class="end flexcc">END</div>
    </div>

    <div class="file-list mt-5">
      <Uploads ref="UploadsRef" @change="fileChange" :tip="t('Uploads.t2')" />
    </div>

    <!-- 维修选项 -->
    <ProjectType v-if="dialogProjectType" :samallId="checkedRow.projectId" :projectParent="checkedRow.projectParent" :visible="dialogProjectType" @close="dialogProjectType = false" @confirm="itemTypeConfirm" />

    <!-- 维修附加项 -->
    <AdditionItem v-if="dialogAdditionItem" :visible="dialogAdditionItem" @close="dialogAdditionItem = false" @confirm="additionItemConfirm" />

    <!-- 管路 -->
    <Pipeline v-if="pipelineDialog" v-model="pipelineDialog" :checkedRow="checkedRow" :ship-type="info.shcwShippingVo.shippingType" @getData="getDetail(false)" />

    <!-- 阀门 -->
    <Valve v-if="valveDialog" v-model="valveDialog" :checkedRow="checkedRow" :ship-type="info.shcwShippingVo.shippingType" @getData="getDetail(false)" />

    <!-- 钢结构 -->
    <SteelStructure v-if="steelStructureDialog" v-model="steelStructureDialog" :checkedRow="checkedRow" @getData="getDetail(false)" />

    <!-- 保存确认 -->
    <Confirm v-if="dialogConfirmSave" :visible="dialogConfirmSave" :title="t('dockRepair.step2page.Confirm.title')" :text="t('dockRepair.step2page.Confirm.text')" :cancelText="t('donNotSaveText')" :confirmText="t('confirmText')" @cancel="handleDelete" @close="dialogConfirmSave = false" @confirm=";(dialogConfirmSave = false), handleSave('back')" />

    <!-- 友情提示 -->
    <Confirm v-if="alertTipDialog" :visible="alertTipDialog" :title="t('dockRepair.tipTit')" @cancel="alertTipDialog = false" @close="alertTipDialog = false" @confirm="alertTipDialog = false">
      <div v-html="t('dockRepair.tip')"></div>
    </Confirm>

    <!-- 保存后设置可查看人员 -->
    <ConfigPerson v-if="dialogConfigPerson" :visible="dialogConfigPerson" :saveType="saveType" :canViewPerson="canViewPerson" @close="dialogConfigPersonClose" @save="isHandleSave = true" />

    <!-- 添加关键词 -->
    <KeyWordList v-if="addKeyWordDialog" v-model="addKeyWordDialog" @getData="getDetail(false)" />
  </div>
</template>

<script setup lang="jsx">
import { ref, unref, watch, computed, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import useDockRepair from '@/stores/dockRepair.js'
import useLogin from '@/stores/login'

import Confirm from '@/components/Confirm.vue' // 确认框
import ProjectType from './ProjectType.vue' // 维修选项
import AdditionItem from './AdditionItem.vue' // 维修附加项
import Pipeline from './Pipeline.vue' // 管路
import Valve from './Valve.vue' // 阀门
import SteelStructure from './SteelStructure.vue' // 钢结构
import ConfigPerson from './ConfigPerson.vue' // 设置可查看人员
import KeyWordList from './KeyWordList.vue' // 关键词

import Uploads from '@/components/Uploads.vue'

import { getDetailApi, updateDockDetailApi, deleteDetailApi, editApi, repairKeywordsListApi, deleteDockOrderApi } from '@/service/dockOrder'
import { uploads } from '@/service/common'
import { setItemNumber } from '@/utils/index'
import useDict from '@/hooks/useDict.js'
import { debounce } from 'lodash'

const router = useRouter()
const route = useRoute()

const { dictData, getDictData } = useDict()
const { t, locale } = useI18n()

watch(locale, (n) => {
  init()
})

const store = useDockRepair()
const { next, back, setOrderInfo, setShip } = store
const storeLogin = useLogin()
const currentRow = ref(null)
onMounted(() => {
  init()
})

// 友情提示
const alertTipDialog = ref(false)
const alertTip = (index) => {
  if (index !== 0) return
  alertTipDialog.value = true
}

// 表单
const ruleForm = ref({
  dockImportProjectBoList: []
})
const rules = ref({})
const setRules = () => {
  rules.value = {
    remark: [{ required: true, message: t('dockRepair.step2page.r1'), trigger: ['blur', 'change'] }],
    quoteOrderCurrency: [{ required: true, message: t('dockRepair.step2page.r5'), trigger: 'change' }],
    payCurrency: [{ required: true, message: t('dockRepair.step2page.r6'), trigger: 'change' }],
    projectId: [{ required: true, message: t('dockRepair.step2page.r2'), trigger: 'change' }],
    projectContent: [{ required: true, message: t('dockRepair.step2page.r3'), trigger: 'blur' }],
    makeCount: [{ required: true, message: t('dockRepair.step2page.r4'), trigger: 'blur' }]
  }
}
// 坞修关键词
const keywordOptions = ref({})
const getKeywordList = () => {
  repairKeywordsListApi().then(({ data }) => {
    keywordOptions.value = data
  })
}
const keywordOptionsDisabled = (item) => {
  return ruleForm.value.dockImportProjectBoList.some((p) => p.projectId && item.id === p.projectId)
}
const addKeyWordDialog = ref(false)

// 维修选项(项目类型)
const dialogProjectType = ref(false)
// 维修选项 确认
const itemTypeConfirm = (value) => {
  // console.log(value)
  const { repairProjectId, parentId, projectName, projectNameCn, projectNameEn, unit, unitCn, unitEn } = value

  const row = tableData.value[editIndex]

  row.projectId = repairProjectId
  row.projectParent = parentId
  row.projectName = projectName
  row.projectNameCn = projectNameCn
  row.projectNameEn = projectNameEn
  row.unit = unit
  row.unitCn = unitCn
  row.unitEn = unitEn
}

// 维修附加项
const dialogAdditionItem = ref(false)
const additionItemConfirm = (value) => {
  const { id, projectName, projectCnName, projectEnName, projectUnit, projectCnUnit, projectEnUnit } = value

  const row = tableData.value[editIndex]

  row.additionalId = id
  row.projectId = null
  row.projectParent = checkedRow.value.projectParent
  row.projectName = projectName
  row.projectNameCn = projectCnName
  row.projectNameEn = projectEnName
  row.unit = projectUnit
  row.unitCn = projectCnUnit
  row.unitEn = projectEnUnit
}

// 下一步 自动保存
const handleNext = () => {
  if (isHandleSave.value) next()
  else handleSave('next')
}

// 返回时
const handleBack = () => {
  dialogConfirmSave.value = true
}

// 保存确认
const dialogConfirmSave = ref(false)

// 删除坞修单
const handleDelete = () => {
  deleteDockOrderApi(store.orderInfo.id).then(({ msg }) => {
    ElMessage.success(msg)
    dialogConfirmSave.value = false
    back()
    router.replace({
      path: route.path
    })
  })
}

// 保存后设置可查看人员
const dialogConfigPerson = ref(false)
const canViewPerson = ref([])
const dialogConfigPersonClose = () => {
  dialogConfigPerson.value = false
  if (saveType.value === 'save') {
    getDetail()
  }
}

// 保存
const formEl = ref(null)
const saveType = ref('save') // save保存  next下一步 back上一步
const isHandleSave = ref(false) // 是否已保存
const handleSave = (type = 'save') => {
  // const data = unref(tableData.value)
  // if (data.some((item) => !item.isSave)) {
  //   ElMessage.warning(t('dockRepair.step2page.w7'))
  //   return
  // } // 空白项目允许保存

  const { shippingName } = store.ship
  const { id, orderNo, dockOrderName, count, nature, countEn, natureEn } = store.orderInfo

  const params = {
    id,
    orderNo,
    ...ruleForm.value
  }

  if (!dockOrderName) {
    if (!count) {
      return ElMessage.warning(t('dockRepair.step2page.w1_1'))
    }
    if (!nature) {
      return ElMessage.warning(t('dockRepair.step2page.w1_2'))
    }
    params.dockOrderName = `${shippingName}${count}${nature}`
    params.dockOrderNameEn = `${shippingName}${' '}${countEn}${' '}${natureEn}`
  }

  if (!formEl.value) return
  formEl.value.validate(async (valid, fields) => {
    if (valid) {
      // params.dockImportProjectBoList.forEach((item) => {
      //   const f = keywordOptions.value.find((o) => o.id === item.projectId)
      //   if (f) {
      //     const { repairKeywordsCn, repairKeywordsEn } = f
      //     item.projectNameCn = repairKeywordsCn
      //     item.projectNameEn = repairKeywordsEn
      //   }

      //   item.dockOrderId = store.orderInfo.id
      // })

      params.urlList = await handleUpload()

      editApi(params).then(() => {
        dialogConfigPerson.value = true
        saveType.value = type
        getDetail()
      })
    }
  })
}

// 正在编辑的 index
let editIndex = null

// 勾选的 行
const checkedRow = ref(null)

// 按钮禁用
const setBtnDiasbled = (dataType) => {
  const _data = unref(tableData.value)
  let flag = false
  if (checkedRow.value === null) {
    flag = true
  } else {
    // 勾选的行级别不为2的  只能点击'说明'
    if (dataType !== '1' && checkedRow.value.projectLevel !== 2) {
      flag = true
    }

    // 自定义
    if (dataType === '2' && ![0, 1].includes(checkedRow.value.projectLevel)) {
      flag = false
    }

    // 附加项
    if (dataType === '3') {
      flag = false
    }
  }
  return flag || _data.some((d) => !d.isSave)
}

// 行 class
const setRowClass = ({ columns, rowData, rowIndex }) => {
  // console.log(columns, rowData, rowIndex, '---')
  let str = ''

  if (rowData.projectLevel !== null) {
    str += ` projectLevel-${rowData.projectLevel}`
  }

  if (!rowData.isSave) {
    str += ' no-save'
  }

  return str
}



// 是否滚动到了底部
const tableRef = ref(null)
const isEnd = ref(false)
const onScroll = ({ scrollTop }) => {
  if (!tableData.value.length) return
  isEnd.value = scrollTop + 700 - 50 > tableData.value.length * 50
}

// 复选框 组件
const SelectionCell = ({ value, intermediate = false, onChange }) => {
  return <ElCheckbox onChange={onChange} modelValue={value} indeterminate={intermediate} />
}
// 获取列
const getColumns = () => {
  const setRef = (el) => {
    if (el) {
      el.focus?.()
    }
  }
  const setEditingClassName = (flag) => {
    return { 'table-v2-inline-editing-trigger': flag }
  }

  // 保存
  const handleRowSave = debounce(
    (rowData) => {


      currentRow.value = rowData
      const params = { ...rowData }




      // 无修改
      if(locale.value === 'zh-CN' && params.projectName === params.projectNameCn){
        console.log(params.projectName, params.projectNameCn, '=============')
        if(rowData.dataType !== '1'){
          params.projectName = undefined
          params.projectNameCn = undefined
          params.projectNameEn = undefined
        }
      }

      if(locale.value === 'zh-CN' && params.unit === params.unitCn){
        params.unit = undefined
        params.unitCn = undefined
        params.unitEn = undefined
      }

      if(locale.value === 'en' && params.projectName === params.projectNameEn){
        params.projectName = undefined
        params.projectNameCn = undefined
        params.projectNameEn = undefined
      }

      if(locale.value === 'en' && params.unit === params.unitEn){
        params.unit = undefined
        params.unitCn = undefined
        params.unitEn = undefined
      }



      if (rowData.dataType === '3') {
        if(locale.value === 'zh-CN' && params.projectName !== params.projectNameCn){
          params.projectNameCn = params.projectNameEn = params.projectName
        }
        if(locale.value === 'zh-CN' && params.unit !== params.unitCn){
          params.unitCn = params.unitEn = params.unit
        }

        if(locale.value === 'en' && params.projectName !== params.projectNameEn){
          params.projectNameCn = params.projectNameEn = params.projectName
        }
        if(locale.value === 'en' && params.unit !== params.unitEn){
          params.unitCn = params.unitEn = params.unit
        }
      }



      if (rowData.dataType === '2') {
        params.projectNameCn = params.projectNameEn = params.projectName
        params.unitCn = params.unitEn = params.unit
      }
      if (rowData.dataType === '1') {
        params.unitCn = params.unitEn = params.unit
      }

      // 无id时 为新增
      if (!params.id) {
        params.previousId = checkedRow.value.id // 上一个明细id(勾选的id)
      }




      // if (params.id) {
      //   params.projectName = undefined
      //   params.projectNameCn = undefined
      //   params.projectNameEn = undefined
      // }

      updateDockDetailApi({
        dockOrderId: store.orderInfo.id, // 坞修单id
        ...params
      }).then(({ data }) => {
        rowData.isSave = true
        var timer = setTimeout(() => {
          clearTimeout(timer)
          timer = null
          rowData.editingKey = null
        }, 100)

        checkedRow.value = null
        editIndex = null
        rowData.id = data
        ElMessage.success(t('saveSuccess'))

        const _data = unref(tableData.value)
        setItemNumber(_data)
      })
    },
    500,
    {
      leading: true, // 延长开始后调用
      trailing: false // 延长结束前调用
    }
  )

  // 回车保存
  const handleEnterSave = (e, rowData) => {
    if (['Enter', 'NumpadEnter'].includes(e.code)) {
      handleRowSave(rowData)
    }
  }

  columns.value = [
    {
      key: 'selection',
      width: 50,
      fixed: 'left',
      align: 'center',
      cellRenderer: ({ rowData }) => {
        const _data = unref(tableData.value)
        const onChange = (value) => {
          _data.forEach((row) => (row.checked = false))
          rowData.checked = value
          checkedRow.value = value ? rowData : null
          currentRow.value = rowData
        }

        if (_data.every((d) => d.isSave)) {
          return <SelectionCell value={rowData.checked} onChange={onChange} />
        }
      }
    },
    {
      title: t('dockRepair.coltit1'), // 项目编号
      key: 'itemNumber',
      dataKey: 'itemNumber',
      width: 100,
      class: 'itemNumber',
      align: 'center'
    },
    {
      title: t('dockRepair.coltit2'),
      key: 'projectName',
      dataKey: 'projectName',
      width: 500,
      cellRenderer: ({ rowData, rowIndex }) => {
        // const isEdit = ['1', '2', '3'].includes(rowData.dataType)
        const isEdit = ['0', '2', '3'].includes(rowData.dataType) && ![0, 1].includes(rowData.projectLevel)

        if (rowData.editingKey === 'projectName') {
          if (isEdit) {
            return (
              <el-input
                ref={setRef}
                v-model={rowData.projectName}
                placeholder=" "
                maxlength={100}
                onChange={() => {
                  handleRowSave(rowData)
                }}
                onKeyup={(e) => handleEnterSave(e, rowData)}
              />
            )
          }
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'projectName'
        }

        return (
          <div class={setEditingClassName(isEdit)} onClick={onEnterEditMode}>
            {rowData.projectName}
          </div>
        )
      }
    },
    {
      title: t('dockRepair.coltit3'), // 项目类型说明
      key: 'projectContent',
      dataKey: 'projectContent',
      width: 200,
      cellRenderer: ({ rowData, rowIndex }) => {
        const isEdit = ['0', '1', '2', '3'].includes(rowData.dataType)

        if (rowData.editingKey === 'projectContent') {
          if (isEdit) {
            return (
              <el-input
                ref={setRef}
                v-model={rowData.projectContent}
                placeholder={t('dockRepair.coltit3_p')}
                maxlength={100}
                onChange={() => {
                  handleRowSave(rowData)
                }}
                onKeyup={(e) => handleEnterSave(e, rowData)}
              />
            )
          }
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'projectContent'
        }

        return (
          <div class={setEditingClassName(isEdit)} onClick={onEnterEditMode}>
            {rowData.projectContent}
          </div>
        )
      }
    },
    {
      title: t('dockRepair.coltit4'), // 单位
      key: 'unit',
      dataKey: 'unit',
      width: 110,
      align: 'center',
      cellRenderer: ({ rowData, rowIndex }) => {
        const isEdit = ['2', '3'].includes(rowData.dataType) && ![0, 1].includes(rowData.projectLevel)

        if (rowData.editingKey === 'unit') {
          if (isEdit) {
            return (
              <el-input
                ref={setRef}
                v-model={rowData.unit}
                placeholder=" "
                maxlength={100}
                onChange={() => {
                  handleRowSave(rowData)
                }}
                onKeyup={(e) => handleEnterSave(e, rowData)}
              />
            )
          }
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'unit'
        }

        return (
          <div class={setEditingClassName(isEdit)} onClick={onEnterEditMode}>
            {rowData.unit}
          </div>
        )
      }
    },
    {
      title: t('dockRepair.coltit5'), // 数量
      key: 'requireCount',
      dataKey: 'requireCount',
      width: 125,
      align: 'center',
      cellRenderer: ({ rowData, rowIndex }) => {
        const isEdit = ['0', '2', '3'].includes(rowData.dataType) && ![0, 1].includes(rowData.projectLevel)

        if (rowData.editingKey === 'requireCount') {
          if (isEdit) {
            const arr = ref([])
            if (rowData.calculdateFormulas) {
              arr.value = rowData.calculdateFormulas.split('输入框').map((item) => ({ str: item, val: null }))
            }
            // console.log(arr.value, '---')

            const res = ref('')
            const viewRes = ref(null)
            watch(
              arr,
              (n) => {
                // console.log(n)

                let str = ''
                n.forEach((item) => {
                  str += item.str + (item.val ? String(item.val) : '')
                })

                // console.log(str, '==')
                res.value = str
                try {
                  viewRes.value = eval(res.value)
                } catch (error) {}
              },
              { deep: true }
            )

            const onConfirm = () => {
              try {
                rowData.requireCount = eval(res.value)
                handleRowSave(rowData)
              } catch (error) {}
            }

            return (
              <>
                <el-input-number
                  ref={setRef}
                  v-model={rowData.requireCount}
                  min={0}
                  max={999999999}
                  controls={false}
                  onChange={() => {
                    if (rowData.calculdateFormulas) return
                    handleRowSave(rowData)
                  }}
                  onBlur={
                    () => {
                      if (rowData.calculdateFormulas) return
                      if(rowData.requireCount) handleRowSave(rowData)
                    }
                  }
                  onKeyup={(e) => handleEnterSave(e, rowData)}
                />

                {rowData.calculdateFormulas ? (
                  <el-popover
                    placement="bottom"
                    width={400}
                    trigger="click"
                    v-slots={{
                      reference: () => (
                        <el-button type="primary" size="small">
                          {t('dockRepair.calculate')}
                        </el-button>
                      ),
                      default: () => (
                        <>
                          <div class="flexsc">
                            {arr.value.map((item, index) => {
                              if (index !== arr.value.length - 1) {
                                return (
                                  <>
                                    <div>{item.str}</div>
                                    <el-input-number v-model={item.val} controls={false}></el-input-number>
                                  </>
                                )
                              }
                            })}
                          </div>
                          <div class="mt-1 flexsb">
                            <div>
                              {res.value}={viewRes.value}
                            </div>
                            <el-button type="primary" size="small" onClick={onConfirm}>
                              {t('confirmText')}
                            </el-button>
                          </div>
                        </>
                      )
                    }}
                  ></el-popover>
                ) : (
                  ''
                )}
              </>
            )
          }
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'requireCount'
        }
        return (
          <div class={setEditingClassName(isEdit)} onClick={onEnterEditMode}>
            {rowData.requireCount}
          </div>
        )
      }
    },
    {
      title: t('dockRepair.coltit6'), // 操作
      width: 120,
      fixed: 'right',
      align: 'center',
      cellRenderer: ({ rowData, rowIndex }) => {
        const _data = unref(tableData.value)

        // 删除
        const handleRowDelete = (value) => {
          if (!rowData.id) {
            _data.splice(rowIndex, 1)
            checkedRow.value = null
            editIndex = null
            setItemNumber(_data)
            return
          }
          // console.log(value)
          deleteDetailApi({
            id: rowData.id
          }).then(({ msg }) => {
            ElMessage.success(msg)
            // _data.splice(rowIndex, 1)
            // setItemNumber(_data)
            checkedRow.value = null
            editIndex = null
            getDetail()
          })
        }
        return (
          <>
            <el-popconfirm
              title={rowData.dataType === '1' ? t('popconfirm_del') : t('dockRepair.step2page.popconfirm_del')}
              width={260}
              v-slots={{
                reference: () => <img src={new URL('@/assets/img/icon_shanchu.png', import.meta.url)} height="22" />
              }}
              onConfirm={handleRowDelete}
            ></el-popconfirm>
          </>
        )
      }
    }
  ]
}

// 表格 列
const columns = ref([])

// 回显(表格数据)
const tableData = ref([])
const info = ref({})
const getDetail = (isUpdate = true) => {
  getDetailApi(store.orderInfo.id).then(({ data }) => {
    const { dockImportProjectBoList, dockOrderDetailBoList, dockOrderName, remark, quoteOrderCurrency, payCurrency, canViewPerson: person, urlList, shcwShippingVo } = data

    info.value = data

    setOrderInfo(data)

    if (dockOrderDetailBoList) {
      dockOrderDetailBoList.forEach((item) => {
        item.checked = item.id === checkedRow.value?.id
        item.isSave = true
      })
      tableData.value = dockOrderDetailBoList
      setItemNumber(dockOrderDetailBoList)
    }

    if (!dockOrderName) {
      setShip(shcwShippingVo)
    }

    // 船舶国籍
    const { nationality } = shcwShippingVo

    // 公司的注册地为国外时
    let qc = '',
      fc = ''
    if (!['中国', 'China'].includes(storeLogin.userInfo.enterpriseCountry)) {
      qc = 'currency_1'
      fc = 'currency_1'
    } else {
      qc = 'currency_0'
      fc = ['中国', 'China'].includes(nationality) ? 'currency_0' : 'currency_1'
    }

    if (isUpdate) {
      ruleForm.value = {
        remark: !remark ? t('dockRepair.statementValue') : remark === '以下维修项目以报价为目的，仅供报价参考使用，实际修理技术要求和工艺要求及验收标准，以船东、船级社、船厂质量标准为主；' || remark === "The main purpose of this list is for yard's quotation, all technical requirements of repair items to be complied with Owner, Class and Yard's quality standards / practice." ? t('dockRepair.statementValue') : remark,
        // dockImportProjectBoList: dockImportProjectBoList || [],
        quoteOrderCurrency: ruleForm.value.quoteOrderCurrency || quoteOrderCurrency || qc,
        payCurrency: ruleForm.value.payCurrency || payCurrency || fc
      }
    }

    if (person) canViewPerson.value = person

    if (urlList) {
      fileList.value = urlList.map((item) => {
        return {
          name: item.file_name,
          url: item.url
        }
      })
    }

    UploadsRef.value.setFileList(fileList.value)
  })
}

// 在选中行下面插入一行
const handleAdd = (dataType) => {
  const _data = unref(tableData.value)
  const index = _data.findIndex((row) => row.checked)
  if (index === -1) {
    return
  }
  _data.forEach((row) => (row.checked = false))

  let obj = {
    isSave: false,
    projectLevel: 2,
    dataType
  }

  if (dataType === '2') {
    obj.projectParent = checkedRow.value.projectParent
    obj.projectLevel = checkedRow.value.projectLevel
    const params = { ...obj }
    // 无id时 为新增
    if (checkedRow.value.id) {
      params.previousId = checkedRow.value.id // 上一个明细id(勾选的id)
    }
    params.editingKey = ''
    updateDockDetailApi({
      dockOrderId: store.orderInfo.id, // 坞修单id
      ...params
    }).then(({ data }) => {
      getDetail()
    })
  }

  if (dataType === '1') {
    obj.projectName = '说明' // 固定为 '说明'
    obj.projectNameCn = '说明'
    obj.projectNameEn = 'explain'
    obj.projectLevel = checkedRow.value.projectLevel
    obj.projectParent = checkedRow.value.projectParent
    obj.projectId = null
  }

  _data.splice(index + 1, 0, obj)
  setItemNumber(_data)
}

// 管路
const pipelineDialog = ref(false)
const handleAddItemPipeline = () => {
  pipelineDialog.value = true
}

// 阀门
const valveDialog = ref(false)
const handleAddItemValve = () => {
  valveDialog.value = true
}

// 钢结构
const steelStructureDialog = ref(false)
const handleAddItemSteelStructure = () => {
  steelStructureDialog.value = true
}

// 文件列表
const fileList = ref([])
const fileChange = (val) => {
  fileList.value = val
}
const UploadsRef = ref(null)
const handleUpload = () => {
  return new Promise((resolve, reject) => {
    const newList = fileList.value.filter((item) => item.raw)
    const oldList = fileList.value
      .filter((item) => !item.raw)
      .map((item) => {
        return {
          url: item.url,
          name: item.name
        }
      })

    if (newList.length) {
      const formData = new FormData()
      newList.forEach((item) => {
        formData.append('files', item.raw)
      })
      uploads(formData).then(({ urls, fileNames }) => {
        const newUrls = urls.split(',')
        fileList.value = newUrls.map((newUrl, newUrlIndex) => {
          return {
            name: fileNames.split(',')[newUrlIndex],
            url: newUrl
          }
        })
        UploadsRef.value.setFileList(fileList.value)
        resolve([
          ...oldList,
          ...newUrls.map((url, index) => {
            return {
              url,
              name: fileNames.split(',')[index]
            }
          })
        ])
      })
    } else {
      resolve(oldList)
    }
  })
}

// 初始化
const init = () => {
  getDictData('currency')
  setRules()
  // getKeywordList() // 关键词
  getColumns() // 列
  getDetail() // 表格数据
}
</script>

<style scoped lang="scss">
.step2 {
  padding-bottom: 36px;
  .el-button {
    min-width: 150px;
  }
  .top {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 1260px;
    padding-top: 30px;
  }

  .grid-1 {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 30px;
  }

  .grid {
    display: grid;
    grid-template-columns: repeat(3, 355px) 105px;
    gap: 15px;
  }
  .keylist {
    .el-form-item {
      margin-bottom: 0;
    }
  }

  .module {
    background: #fff;
    padding: 24px;
    .title {
      border-bottom: #252628 2px solid;
      color: #252628;
      padding-bottom: 10px;
    }
  }

  .keyword .con {
    gap: 20px;
    .item {
      cursor: default;
      color: #252628;
      background: #f0f3f8;
      padding: 15px 40px;
      border-radius: 4px;
    }

    .item:last-child {
      margin-right: auto;
    }
  }

  .list {
    background: #fff;
    padding: 24px;

    .end {
      height: 35px;
      border-bottom: 1px solid #ebeef5;
    }

    .table {
      border-top: 2px solid #252628;
      height: 700px;

      :deep(.table-v2-inline-editing-trigger) {
        border: 1px transparent dotted;
        padding: 4px;
        min-height: 26px;
        min-width: 100%;
        cursor: text;
        border-radius: 3px;
      }

      :deep(.table-v2-inline-editing-trigger:hover) {
        border-color: var(--el-color-primary);
      }
      :deep(.el-table-v2__header-cell) {
        background: #f0f3f8;
        color: #252628;
      }
      :deep(.no-save) {
        background: #f9ecd9;
      }
      :deep(.projectLevel-0) {
        background: #f7f9fb;
      }

      :deep(.projectLevel-0),
      :deep(.projectLevel-1),
      :deep(.projectLevel-2) {
        .itemNumber {
          justify-content: center;
        }
      }
      :deep(.projectLevel-3),
      :deep(.projectLevel-4) {
        .itemNumber {
          justify-content: right;
        }
      }

      // &.en {
      :deep(.el-table-v2__header-cell) {
        font-family: 'Sitka Display Semibold';
        justify-content: center;
        * {
          font-size: 17px;
        }
      }

      :deep(.projectLevel-0) {
        font-family: 'Amasis MT Pro Medium';
        * {
          font-size: 17px;
          font-weight: bold;
        }
      }
      :deep(.projectLevel-1) {
        font-family: '等线';
        * {
          font-size: 16px;
          font-weight: bold;
        }
      }

      :deep(.projectLevel-2, .projectLevel-3, .projectLevel-4) {
        font-family: 'Abadi';
        * {
          font-size: 15px;
        }
      }
      // }
    }
  }
}
</style>
